package com.dongdongshop.config;
import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import java.util.LinkedHashMap;
import java.util.Map;

@Configuration
public class ShiroConfig {
    @Bean
    public ShiroFilterFactoryBean shiroFilterFactoryBean(@Autowired DefaultWebSecurityManager webSecurityManager){
        ShiroFilterFactoryBean filterFactoryBean = new ShiroFilterFactoryBean();
        filterFactoryBean.setSecurityManager(webSecurityManager);
        Map<String,String> map = new LinkedHashMap<>();
        map.put("/login","anon");       //放过登录页面
        map.put("/sellerLogin","anon");       //放过登录页面
//        map.put("/uulogin","anon");       //放过登录页面

        //拦截所有
//        map.put("/**","authc");
        filterFactoryBean.setFilterChainDefinitionMap(map);
        //被拦截的页面都跳转到登录页面
        //filterFactoryBean.setLoginUrl("/skipLogin");   //如果没登录跳转到~
        filterFactoryBean.setUnauthorizedUrl("/unauthorized");   //设置权限
        return filterFactoryBean;
    }

    @Bean
    public DefaultWebSecurityManager defaultWebSecurityManager(@Autowired LoginRealm loginRealm){
        DefaultWebSecurityManager webSecurityManager = new DefaultWebSecurityManager();
        webSecurityManager.setRealm(loginRealm);
        return webSecurityManager;
    }
    @Bean
    public LoginRealm loginRealm(@Autowired HashedCredentialsMatcher hashedCredentialsMatcher){
        LoginRealm loginRealm = new LoginRealm();
        loginRealm.setCredentialsMatcher(hashedCredentialsMatcher);
        return loginRealm;
    }

    @Bean
     public HashedCredentialsMatcher hashedCredentialsMatcher(){
         HashedCredentialsMatcher matcher = new HashedCredentialsMatcher();
         matcher.setHashAlgorithmName("MD5");   //加密方式
         matcher.setHashIterations(3);    //加盐次数
         matcher.setStoredCredentialsHexEncoded(true);  //编码
         return matcher;
     }
}